<template>
  <el-dialog
    v-if="dialogVisible"
    width="400px"
    :title="title"
    :lock-scroll="false"
    :visible.sync="dialogVisible"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    @close="handleClose"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item prop="name" label="分类名称">
        <el-input v-model="form.name" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item prop="sorted" label="排序">
        <el-input-number v-model="form.sorted" class="w_100" :min="1" :max="9999" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { add, edit, getInfo } from '@/api/client/clientCategory'

export default {
  name: 'SaveOrEditVue',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'add'
    },
    id: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      title: '新增',
      form: {
        name: '',
        sorted: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        sorted: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    switch (this.type) {
      case 'add':
        this.title = '新增'
        break
      case 'edit':
        this.title = '编辑'
        getInfo(this.id).then(res => {
          this.form = res.data
        })
        break
      default:
        break
    }
  },
  methods: {
    handleSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          switch (this.type) {
            case 'add':
              add(this.form).then(res => {
                this.$message.success('添加成功')
                this.handleGetList()
                this.handleClose()
              })
              break
            case 'edit':
              edit(this.form).then(res => {
                this.$message.success('编辑成功')
                this.handleGetList()
                this.handleClose()
              })
              break
            default:
              break
          }
        }
      })
    },
    handleGetList() {
      this.$emit('getList')
    },
    handleClose() {
      this.$emit('handleClose')
    }
  }
}
</script>

<style scoped lang="scss">

</style>
